package cn.mickey.exchange.config;

import cn.mickey.exchange.properties.TaskThreadPoolProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Task类的线程配置
 * @author mickey
 */
@Configuration
public class TaskExecutorConfig {

    @Resource
    private TaskThreadPoolProperties properties;
    /**
     *普通模式
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        return initTaskExecutor(
                properties.getCorePoolSize(),
                properties.getMaxPoolSize(),
                properties.getQueueCapacity(),
                properties.getKeepAliveSeconds(),
                properties.getThreadNamePrefix(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    /**
     * 初始化TaskExecutor
     *
     * @param corePoolSize             int 默认线程数
     * @param maxPoolSize              int 最大线程数
     * @param queueCapacity            int 缓冲队列长度
     * @param keepAliveSecond          int 允许空闲时间
     * @param namePrefix               String  名称的前缀
     * @param rejectedExecutionHandler 线程池满的时候如何处理
     * @return ThreadPoolTaskExecutor
     */
    private ThreadPoolTaskExecutor initTaskExecutor(int corePoolSize, int maxPoolSize,
                                                    int queueCapacity, int keepAliveSecond, String namePrefix,
                                                    RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数(默认线程数)
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //缓冲队列数
        executor.setQueueCapacity(queueCapacity);
        //允许线程空闲时间(单位默认为秒)
        executor.setKeepAliveSeconds(keepAliveSecond);
        //线程名前缀
        executor.setThreadNamePrefix(namePrefix);

        //线程池对拒绝任务的处理策略，
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);

        //初始化
        executor.initialize();
        return executor;
    }
}
